package com.sky.task;

import com.sky.entity.Order;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void cancelOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        //判断未支付订单时间是否小于当前时间减15分钟
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(15);
        List<Order> orderList = orderMapper.selectByStatusAndOrderTimeLT(Order.PENDING_PAYMENT, orderTime);
        if (orderList != null && !orderList.isEmpty()){
            orderList.forEach(order -> {
                Order orders = Order.builder()
                        .id(order.getId())
                        .status(Order.CANCELLED)
                        .cancelReason("订单超时，自动取消")
                        .cancelTime(LocalDateTime.now())
                        .build();
                        orderMapper.update(orders);
            });
        }
    }

    @Scheduled(cron = "0 0 1 * * ? ")
    public void completeOrder(){
        log.info("定时处理待派单的订单：{}", LocalDateTime.now());
        //判断订单状态为待派单的订单时间是否小于当前时间减1天
        LocalDateTime orderTime = LocalDateTime.now().plusHours(-1);
        List<Order> orderList = orderMapper.selectByStatusAndOrderTimeLT(Order.DELIVERY_IN_PROGRESS, orderTime);
        if (orderList != null && !orderList.isEmpty()) {
            orderList.forEach(order -> {
                Order orders = Order.builder()
                        .id(order.getId())
                        .status(Order.COMPLETED)
                        .build();
                orderMapper.update(orders);
            });
        }
    }
}
